import { useEffect, useRef } from 'react'
import style from './index.module.less'
import { Space, Button, Dropdown, Menu, Form, FormInstance, Input, Select, DatePicker, message } from 'antd'
import { PDFParamSchema, PDFSchema } from '@src/components/schema/pdf'
import moment, { Moment } from 'moment'
import { awaitWrap } from '@src/assets/js/tool'
import { updateRequest } from './ajax'

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

async function reCreateHandle (v: { [k: string]: any }, caseid: string, fileid: string, formParamsHidden: PDFParamSchema[], formParamsMap: { [k: string]: PDFParamSchema }, refreshFn: () => void) {
  const p: Array<{[k: string]: any}> = formatFormData(v, formParamsHidden, formParamsMap)
  const hide = message.loading('重新生成中', 120)
  p.forEach(li => {
    if (li.parm_value === '') {
      li.parm_value = null
    }
  })
  const [e] =  await awaitWrap(updateRequest(caseid, fileid, p))
  hide()
  if (e === null) {
    refreshFn()
  }
}

// 格式化表单值
function formatFormData (v: { [k: string]: any }, formParamsHidden: PDFParamSchema[], formParamsMap: { [k: string]: PDFParamSchema } ) {
  const keys = Object.keys(v)
  const result: PDFParamSchema[] = []
  keys.forEach(key => {
    const o = formParamsMap[key] || {}
    let value = v[key] === undefined ? '' : v[key]
    if (value instanceof Array) {
      value = value.join(',')
    } else if (value instanceof moment) {
      value = (value as Moment).format(o.parm_type_data || 'YYYY年MM月DD日')
    }
    result.push({
      id: o.id,
      parm_key: o.parm_key,
      parm_value: value
    } as PDFParamSchema)
  })
  formParamsHidden.forEach(li => {
    result.push({
      id: li.id,
      parm_key: li.parm_key,
      parm_value: li.parm_value
    } as PDFParamSchema)
  })
  return result
}

interface Props {
  caseid: string
  fileid: string
  file: PDFSchema | null
  editable: boolean
  formParams: PDFParamSchema[]
  formInitData: {[k: string]: any}
  isSeal: boolean
  formParamsHidden: PDFParamSchema[]
  formParamsMap: { [k: string]: PDFParamSchema }
  refreshFn: () => void
}

function Main ({ caseid, fileid, file, editable, formParams, formInitData, isSeal, formParamsHidden, formParamsMap, refreshFn }: Props) {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    if (formRef.current) {
      formRef.current.setFieldsValue(formInitData)
    }
  }, [formRef, formInitData])
  return (
    <div className={style.container}>
      <div className={style['right-box-params-list']}>
        <Form layout='vertical' initialValues={formInitData} ref={formRef} onFinish={v => { reCreateHandle(v, caseid, fileid, formParamsHidden, formParamsMap, refreshFn) }}>
          {
            formParams.map((li, i) => {
              return (
                <Item key={li.id} name={li.parm_key} label={`${i + 1}. ${li.parm_key}`}>
                  {renderItemInput(li)}
                </Item>
              )
            })
          }
          {editable && <Button type='primary' htmlType='submit'>保存</Button>}
        </Form>
      </div>
    </div>
  )
}

function Text ({ value }: { value?: string }) {
  return <span>{value || '暂无'}</span>
}

function renderItemInput ( data: PDFParamSchema ) {
  let options: Array<{ value: string, title: string }> = []
  if ((data.parm_type_data as any) instanceof Array) {
    options = data.parm_type_data as unknown as Array<{ value: string, title: string }>
  }
  switch (data.parm_input_type) {
    case '文本框':
      return (<Input placeholder='请输入' />)
    case '文本域':
      return (<TextArea placeholder='请输入' />)
    case '单选选择器':
      return (
        <Select placeholder='请选择'>
          {
            options.map((li, i) => (
              <Option key={i} value={li.value}>{li.title}</Option>
            ))
          }
        </Select>
      )
    case '多选选择器':
      return (
        <Select placeholder='请选择' mode='multiple'>
          {
            options.map((li, i) => (
              <Option key={i} value={li.value}>{li.title}</Option>
            ))
          }
        </Select>
      )
    case '时间选择器':
      return (<DatePicker className={style.full} placeholder='请选择' />)
    default:
      return (<Text />)
  }
}

export default Main
